// pages/feedback/feedback.js
const app = getApp(), core = require('../../utils/core'), util = require('../../utils/util'), WeValidator = require('../../utils/we-validator');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    feedbackReasons: [],
    maxImage: 5,
    images: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    core.get({url:'xilujob.feedback/feedback_reasons',success:ret=>{
      this.setData({feedbackReasons: ret.data.feedback_reasons});
    }})
  },
  //上传轮播图
  uploadImages() {
    let page = this;
    let availableCount = page.data.maxImage - page.data.images.length;
    if(availableCount<1) {
      wx.showToast({title: '最多5张图片',icon:'none'});
      return;
    }
    wx.chooseImage({
      count: availableCount,
      success: res => {
        res.tempFiles.forEach(function(file){
          core.uploadFile({
            filePath: file.path,
            success(ret, response) {
              page.data.images.push(ret.data.url);
              page.setData({images: page.data.images});
            }
          });
        });
      }
    });
  },
  removeImage(event) {
    let index = event.currentTarget.dataset.index;
    this.data.images.splice(index, 1);
    this.setData({images: this.data.images});
  },
  bindSelectReason(event) {
    let index = event.currentTarget.dataset.index;
    this.setData({reason: this.data.feedbackReasons[index].name});
  },
  bindSubmit(event) {
    let data = event.detail.value;
    let validator = new WeValidator({
      rules: {
        content: {required:true},
        contact: {required:true},
        reason: {required:true},
      },
      messages: {
        content: {required:'请填写反馈内容'},
        contact: {required:'请填写联系方式'},
        reason: {required:'请选择反馈类型'},
      }
    });
    if(!validator.checkData(data)) {
      return;
    }
    data.images = this.data.images.join(',');
    core.post({url:'xilujob.feedback/feedback',data:data,success:ret=>{
      wx.navigateBack();
      wx.showToast({title: '感谢您的反馈',icon:'none'});
    }});
  }

});
